package server;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import ocsf.server.ConnectionToClient;

import client.Main;
import client.User;

public class Threads extends Thread 
{
	public SendToClient stc = null;
	public Map <ConnectionToClient, User> users = new HashMap<ConnectionToClient, User>();
	
	public Threads(){}
	
	public void addClient(User usr, ConnectionToClient c)
	{
		users.put(c, usr);
		System.out.println("User id in: "+users.get(c).getID());
	}
	 
	public void removeClient(ConnectionToClient c)
	{
		if(users.containsValue(c) == true)
		{
			System.out.println("User id out: "+users.get(c).getID());
			users.remove(c);
		}
	}
	
	public void setUserStatus(ConnectionToClient c, String status)
	{
		System.out.println("User is frozen: "+users.get(c).getID());
		users.get(c).setStatus(status);
	}
	
	public void run() 
	{
		Object[][] result = null;
		Object[] logedin = null;
		java.sql.Connection conn = null;

		while(true)
		{
			try 
			{
				conn = DriverManager.getConnection(Main.sets[0], Main.sets[1], Main.sets[2]);
				result = DBcheck.getUserDetails("get frozen accounts", conn);
			}catch (SQLException e1) {e1.printStackTrace();}
				
			
			
			try{sleep(2000);}//5 seconds
			catch (InterruptedException e) {e.printStackTrace();}
			
			if(result != null)	
				for(ConnectionToClient c: users.keySet())
					for(int i = 0 ; i < result.length ; i++)
						if(users.get(c).getID() ==  (Long)result[i][0])
							users.get(c).setStatus("FROZEN");
	
			for(ConnectionToClient c: users.keySet())
			{							
				if(users.get(c).getStatus().equals("FROZEN"))
				{
					System.out.println("User: "+users.get(c).getID()+" is FROZEN");
					try 
					{
						stc = new SendToClient("FROZEN");
						stc.uid = users.get(c).getID();
						users.remove(c);
						c.sendToClient(stc);
						break;
					} 
					catch (IOException e) 
					{
						System.out.println("cant send msg to client");
						e.printStackTrace();
					}
				}
			}
			
			try{sleep(1000);}//5 seconds
			catch (InterruptedException e) {e.printStackTrace();}
		}
    }
}
